<template>
    <!-- 干部请假统计 -->
    <van-pull-refresh v-model="refreshLoading" @refresh="onRefresh" >
        <div class="askLeaveRpt1Wrapper">

            <div class="chartTitleLayout">
                <SectionTitle text="干部请假人数统计" />                
                <ApostLevelSelect @select="handelSelect" :value="postLevel"/>
            </div>

            <ButtonGroup :buttons="btns"  style="margin-top: 20px;margin-bottom: 10px;" @select="handleSelctDate"/>


            <div id="askLeaveRpt1"></div>

            
        </div>
    </van-pull-refresh>

    <van-popup v-model:show="showDetail" closeable position="bottom" :style="{ height: '70%' }" teleport="body" round destroy-on-close>
        <AskLeavePopup :date="askLeaveDateDetail" :type="askLeaveTypeDetail" :dateDuration="dateDuration"/>
    </van-popup>
    
</template>
<script lang="ts" setup>
import {type ECOption,initChart} from '@/util/echartsTool'
import { onMounted, onUnmounted } from 'vue';
import { type EChartsType } from 'echarts/core';
import SectionTitle from '@/components/SectionTitle.vue';
import ButtonGroup from '@/components/buttonGroup.vue';
import ApostLevelSelect from '../form/apostLevelSelect.vue';
import { ref } from 'vue';
import { formateDateYMD } from '@/util/dateTool';
import http from '@/api/request'
import AskLeavePopup from '@/views/dashboard/rptPopup/askLeavePopup.vue';
import { saveLog } from '@/api/queryLog';

const refreshLoading = ref(false);


const begin = ref();
const end = ref();
const postLevel = ref('')
const showDetail = ref(false)
const btns = ref(['近1周','近2周','近1月'])
const dateDuration = ref(0);
const askLeaveDateDetail = ref('')
const askLeaveTypeDetail = ref('')


interface AskLeaveRptDataRpt1 {
    date_on:string
    level1_count:number
    level2_count:number
    level3_count:number
    toal_count:number
}


interface AskLeaveRptDataRpt2 {
    task_type:string
    cnt:number    
}

interface AskLeaveRptData{
    rpt1:AskLeaveRptDataRpt1[]
    rpt2:AskLeaveRptDataRpt2[]
}

const handleSelctDate = (index:number)=>{
    dateDuration.value = index;
    saveLog("干部请假报表查询(日期)","rpt_click_askleave",btns.value[index])
    getData();
}

const data = ref(  [
   
  ],)

const option: ECOption = {
    
    tooltip: {
        trigger: 'item',
        triggerOn:'click',
        enterable:true,
        //alwaysShowContent:true,
        formatter: function (params:any) {
            // 返回一个包含 HTML 按钮的字符串
            return `
                <div class="chartsShowDetailBtnWrapper" data-param='${params.name}' >
                    <div data-param='${params.name}' >${params.name}</div>
                    <div data-param='${params.name}'>请假人数: ${params.value}人</div>
                    <div class='chartsShowDetailBtn' style='color:blue' data-param='${params.name}' >查看详情</div>
                </div>
            `;
        },
        
    },
    //@ts-ignore
    xAxis: {
        data: [],
        axisLabel:{
            
            formatter:(value:string,index:string)=>{
                return value;
            }
        }
    },
    yAxis: {
        minInterval:1
    },
    grid: [
    {
      top: 10,
      width: '90%',
      bottom: '50%',
      left: 10,
      containLabel: true
    },
    
    ],
  
    series: [
        {
            name: '请假人数',
            type: 'bar',            
            data: [5, 20, 36, 10, 10, 20],
            tooltip: {
                //formatter:'{a}<br />{b}：{c}人',
                
                
            },
            
        },
        {
            type: 'pie',
            radius: [20, 60],            
            top:340,
            left: 'left',
            width:'100%',
            itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
            },
            data:data.value,
            label: {
                alignTo: 'edge',
                formatter: '{b}\n{c}人',
                minMargin: 4,
                edgeDistance: 40,                
                fontSize:13,
                lineHeight:26                
            },
            labelLine: {
                length: 5,
                length2: 0,
                maxSurfaceAngle: 80
            },
            labelLayout: function (params:any) {

                const labelRect =  params.labelRect;
                const rect = params.rect;           

                const isLeft = params.labelRect.x < myChart.getWidth() / 2;
                const points = params.labelLinePoints;
                // Update the end point.
                points[2][0] = isLeft? params.labelRect.x  : params.labelRect.x + params.labelRect.width;
                return {
                    labelLinePoints: points,
                    labelRect:labelRect,
                    rect:rect
                };
            },    
            tooltip: {
                trigger: 'item',
                triggerOn:'click',
                enterable:true,                
                formatter: function (params:any) {
                    // 返回一个包含 HTML 按钮的字符串
                    return `
                        <div class='chartsShowDetailBtnLeaveTypeWrapper' data-param='${params.name}'>
                            <div data-param='${params.name}'>${params.name}</div>
                            <div data-param='${params.name}'>请假人数: ${params.value}人</div>
                            <div class='chartsShowDetailBtnLeaveType' style='color:blue' data-param='${params.name}'>查看详情</div>
                        </div>
                    `;
                },                
            }     
        }
    ]
};
var myChart :EChartsType;

const onRefresh =()=>{
    getData();
}

onMounted(()=>{

    
    init();

    getData();

    myChart.on('showTip',()=>{
       
        const tooltipsWrapper = document.querySelector('.chartsShowDetailBtnWrapper');
        if(tooltipsWrapper){
            tooltipsWrapper.addEventListener('click',(e:any)=>{
                    const tagrget = e.target as HTMLElement;

                    console.log(tagrget)

                    const res = tagrget.getAttribute('data-param');                

                    console.log(res)

                    showDetail.value = true;
                    askLeaveDateDetail.value = res+"";
                    askLeaveTypeDetail.value =''
                    saveLog("点击干部请假报表（日期）",'rpt_click_item_ask_leave',res+"");
                }
            )            
        }

        const tooltips2 = document.querySelector('.chartsShowDetailBtnLeaveTypeWrapper');
        if(tooltips2){
            tooltips2.addEventListener('click',(e)=>{
                const tagrget = e.target as HTMLElement;
                const res = tagrget.getAttribute('data-param');                
                showDetail.value = true;
                askLeaveTypeDetail.value = res+"";
                askLeaveDateDetail.value = "";
                saveLog("点击干部请假报表(任务类型)",'rpt_click_item_ask_leave',res+"");
            })

         }
    })
})
 

onUnmounted(()=>{
    myChart.dispose();
})

const handelSelect = (postLeve:string)=>{
    postLevel.value = postLeve;
    saveLog("干部请假报表查询(职务级别)","rpt_click_askleave",postLeve)
    getData();
}

const getData = ()=>{

    refreshLoading.value = true;

    begin.value = formateDateYMD(new Date());
    var d = new Date();
    if(dateDuration.value == 0){
        d.setDate(d.getDate()+7)
        end.value = formateDateYMD(d);
    }
    if(dateDuration.value == 1){
        d.setDate(d.getDate()+14)
        end.value = formateDateYMD(d);
    }
    if(dateDuration.value == 2){
        d.setDate(d.getDate()+30)
        end.value = formateDateYMD(d);
    }

    http.get<AskLeaveRptData>('/askleave/rpt',{
        begin:begin.value,
        end:end.value,
        level:postLevel.value
    }).then((resp)=>{
        
        refreshLoading.value = false;

        var tmp:any[]  = [];
        var x:string[] = [];
        var y:number[] = [];
        resp.data?.rpt2.forEach((item)=>{
            tmp.push({
                name:item.task_type,
                value:item.cnt
            })
        })

        //@ts-ignore
        option.series[1].data = tmp


        var maxCount = 0;
        resp.data?.rpt1.forEach((item)=>{
           x.push(item.date_on)

           var theCount = item.toal_count;
           if(postLevel.value == "")theCount = item.toal_count;
           if(postLevel.value == "1")theCount = item.level1_count;
           if(postLevel.value == "2")theCount = item.level2_count;
           if(postLevel.value == "3")theCount = item.level3_count;
           
           if(theCount >= maxCount) maxCount = theCount;
           y.push(theCount);
        })

        //@ts-ignore
        option.xAxis.data = x;
        //@ts-ignore
        option.series[0].data = y;

        if(maxCount == 1){
            //@ts-ignore
            //option.yAxis.data = [1];
        }

        myChart.setOption(option);
    })
}

const init = ()=>{
    // 基于准备好的dom，初始化echarts实例
    myChart = initChart(document.getElementById('askLeaveRpt1'));
    
    // 绘制图表
    myChart.setOption(option);
}
</script>
<style lang="less" scoped>
  .askLeaveRpt1Wrapper{
        background-color: #fff;
        padding:10px;
        margin:10px;
        border-radius: 6px;
        #askLeaveRpt1{
            width: 100%;
            height: 600px;
        }
    }

    .chartTitleLayout{
        display: flex;
        justify-content: space-between;
    }

    .total{
        color:blue;
        padding:10px ;
        font-size: 16px;
        text-align: center;
        
    }
</style>